
const router = require("express").Router();
const webResult = require("./web-result");
const db = require("./db");
const path = require("path");
const fs = require("fs");
const articleService  = require("./service/article-service");
const minIO = require("./min-io");

const pageSize = 10;

const RSSDirectoryPath = path.join(__dirname, "../cyue-share-resource/rss");
const RSSFilePath = path.join(RSSDirectoryPath, "rss.xml");
if (!fs.existsSync(RSSDirectoryPath))
    fs.mkdirSync(RSSDirectoryPath);


router.get("/rss", (_request, response) => {
    try {
        const content = fs.readFileSync(RSSFilePath, "utf-8");
        response
            .header("Content-Type", "")
            .send(content);
    } catch (e) {
        console.error(e);
        response.status(500).render("message", {
            title: "500",
            message: "服务器内部错误"
        });
    }
});

module.exports = {
    router: router,
    async makeRSSFile() {
        let content = `<?xml version="1.0" encoding="UTF-8" ?>
        <rss version="2.0"
            xmlns:atom="http://www.w3.org/2005/Atom"
            xmlns:content="http://purl.org/rss/1.0/modules/content/"
            xmlns:dc="http://purl.org/dc/elements/1.1/"
            xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
        >
        <channel>
            <atom:link href="http://rss.cyue.net" rel="self" type="application/rss+xml" />
            <title>尘跃的个人分享网</title>
            <link>http://cyue.net</link>
            <description>尘跃的个人分享网</description>
            <language>zh-CN</language>
            <lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
            <copyright>Copyright 2023-2024 cyue All Rights Reserved</copyright>
            <managingEditor>1484205856@qq.com (Weifei)</managingEditor>
        `;
    
        // const date = new Date();
        // const today = `${date.getFullYear()}/${(date.getMonth + 1)}/${date.getDate()}`;
        const result = await db.query("select * from article_sort");
        for (let index = 0; index < result.length; index++)
        {
            const element = result[index];
    
            const articleResult = await db.query(
                "select id from article where sort_id = ? order by update_time desc limit ?",
                [element.id, pageSize]
            );
            const articleIDs = new Array(articleResult.length);
            for (let j = 0; j < articleResult.length; j++) {
                articleIDs[j] = articleResult[j].id;
            }
    
            const articleArray = await articleService.getArticleArrayByIDs(articleIDs);
            if (!articleArray)
                continue;
            if (articleArray)
            for (let j = 0; j < articleArray.length; j++)
            {
                const article = articleArray[j];
                if (article.content instanceof Array)
                    article.content = articleService.articleContentJSON2HTML(article.content);
    
                article.content = article.content.replace(/src="\/resource\/([^"]*)"/gi, `src="${minIO.serverURL}/$1"`);
                const date = new Date(article.update_time).toUTCString();
                content += `
                <item>
                    <title>${element.name}——${article.title}</title>
                    <link>http://cyue.net/pages/article/${article.id}</link>
                    <category>${element.name}</category>
                    <guid>http://cyue.net/pages/article/${article.id}</guid>
                    <pubDate>${date}</pubDate>
                    <description><![CDATA[${article.author}——${article.title}]]></description>
                    <dc:creator><![CDATA[${article.author}]]></dc:creator>
                    <content:encoded><![CDATA[${article.content}]]></content:encoded>
                </item>
                `;
            }
        }
        
        content += `
        </channel>
        `;
        content += `</rss>`;
    
        fs.writeFileSync(
            RSSFilePath,
            content,
            "utf-8"
        );
    },


    run() {
        const that = this;
        that.makeRSSFile();
        setInterval(
            () => {
                that.makeRSSFile();
            },
            1000 * 60 * 60 * 12
        )
    }
};


